<template>
  <div class="register">
    <div class="register__container">
      <h2 style="text-align: center; margin-bottom: 2rem">注册账号</h2>

      <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="nickname">
          <el-input v-model="ruleForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="rePassword">
          <el-input v-model="ruleForm.rePassword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doRegister">立即注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {defineComponent, reactive} from '@vue/composition-api';
import {register} from '../../api/user';
import { useNav } from '../../hooks';
import { Message } from 'element-ui';
import {RouterMap} from "../../utils/constants";

const rules = {
  nickname: [{required: true, message: '请输入账号', trigger: 'blur'}],
  password: [{required: true, validator: validatePass, trigger: 'blur'}],
  rePassword: [{required: true, validator: validatePass2, trigger: 'blur'}]
};

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else {
    if (this.ruleForm.password !== '') {
      this.$refs.ruleForm.validateField('password');
    }
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== this.ruleForm.password) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};


export default defineComponent({
  setup(props, {emit,root}) {

    const { to } = useNav({ root });

    const ruleForm = reactive({
      nickname: '',
      password: '',
      phone: '',
      rePassword: '',
    });

    const doRegister = async () => {
      register(ruleForm.nickname, ruleForm.phone, ruleForm.password)
          .then(response => {
            Message({
              message: '注册成功',
              type: 'success'
            })
            to(RouterMap.Home);
          })
    };


    return {
      ruleForm,
      rules,
      doRegister,
      validatePass,
      validatePass2
    };
  },
});
</script>

<style lang="less" scoped>
.register {
  width: 800px;
  margin: 0 auto;

  &__container {
    padding: 4rem;
  }
}
</style>
